{
  "properties" : { },
  "id" : "a68289b7ad374a6386a00dc245656322",
  "script" : null,
  "groupId" : "08c2af4fd56543e690b14515d83d66ae",
  "name" : "mongoTemplete聚合查询",
  "createTime" : null,
  "updateTime" : 1649254796283,
  "lock" : null,
  "createBy" : null,
  "updateBy" : "admin",
  "path" : "aaaaasdasd",
  "method" : "GET",
  "parameters" : [ ],
  "options" : [ ],
  "requestBody" : "",
  "headers" : [ ],
  "paths" : [ ],
  "responseBody" : "{\n    \"code\": 200,\n    \"message\": \"success\",\n    \"data\": [{\n        \"_id\": \"623d836c8422670a040dcb8b\",\n        \"name\": \"李四\",\n        \"age\": 14,\n        \"storeName\": \"麻将馆\",\n        \"store\": [{\n            \"name\": \"麻将馆\",\n            \"isdel\": 0,\n            \"age\": 6\n        }, {\n            \"name\": \"按摩院\",\n            \"isdel\": 1,\n            \"age\": 2\n        }]\n    }],\n    \"timestamp\": 1649254781310,\n    \"executeTime\": 62\n}",
  "description" : null,
  "requestBodyDefinition" : null,
  "responseBodyDefinition" : {
    "name" : "",
    "value" : "",
    "description" : "",
    "required" : false,
    "dataType" : "Object",
    "type" : null,
    "defaultValue" : null,
    "validateType" : "",
    "error" : "",
    "expression" : "",
    "children" : [ {
      "name" : "code",
      "value" : "200",
      "description" : "",
      "required" : false,
      "dataType" : "Integer",
      "type" : null,
      "defaultValue" : null,
      "validateType" : "",
      "error" : "",
      "expression" : "",
      "children" : [ ]
    }, {
      "name" : "message",
      "value" : "success",
      "description" : "",
      "required" : false,
      "dataType" : "String",
      "type" : null,
      "defaultValue" : null,
      "validateType" : "",
      "error" : "",
      "expression" : "",
      "children" : [ ]
    }, {
      "name" : "data",
      "value" : "",
      "description" : "",
      "required" : false,
      "dataType" : "Array",
      "type" : null,
      "defaultValue" : null,
      "validateType" : "",
      "error" : "",
      "expression" : "",
      "children" : [ {
        "name" : "",
        "value" : "",
        "description" : "",
        "required" : false,
        "dataType" : "Object",
        "type" : null,
        "defaultValue" : null,
        "validateType" : "",
        "error" : "",
        "expression" : "",
        "children" : [ {
          "name" : "_id",
          "value" : "623d836c8422670a040dcb8b",
          "description" : "",
          "required" : false,
          "dataType" : "String",
          "type" : null,
          "defaultValue" : null,
          "validateType" : "",
          "error" : "",
          "expression" : "",
          "children" : [ ]
        }, {
          "name" : "name",
          "value" : "李四",
          "description" : "",
          "required" : false,
          "dataType" : "String",
          "type" : null,
          "defaultValue" : null,
          "validateType" : "",
          "error" : "",
          "expression" : "",
          "children" : [ ]
        }, {
          "name" : "age",
          "value" : "14",
          "description" : "",
          "required" : false,
          "dataType" : "Integer",
          "type" : null,
          "defaultValue" : null,
          "validateType" : "",
          "error" : "",
          "expression" : "",
          "children" : [ ]
        }, {
          "name" : "storeName",
          "value" : "麻将馆",
          "description" : "",
          "required" : false,
          "dataType" : "String",
          "type" : null,
          "defaultValue" : null,
          "validateType" : "",
          "error" : "",
          "expression" : "",
          "children" : [ ]
        }, {
          "name" : "store",
          "value" : "",
          "description" : "",
          "required" : false,
          "dataType" : "Array",
          "type" : null,
          "defaultValue" : null,
          "validateType" : "",
          "error" : "",
          "expression" : "",
          "children" : [ {
            "name" : "",
            "value" : "",
            "description" : "",
            "required" : false,
            "dataType" : "Object",
            "type" : null,
            "defaultValue" : null,
            "validateType" : "",
            "error" : "",
            "expression" : "",
            "children" : [ {
              "name" : "name",
              "value" : "麻将馆",
              "description" : "",
              "required" : false,
              "dataType" : "String",
              "type" : null,
              "defaultValue" : null,
              "validateType" : "",
              "error" : "",
              "expression" : "",
              "children" : [ ]
            }, {
              "name" : "isdel",
              "value" : "0",
              "description" : "",
              "required" : false,
              "dataType" : "Integer",
              "type" : null,
              "defaultValue" : null,
              "validateType" : "",
              "error" : "",
              "expression" : "",
              "children" : [ ]
            }, {
              "name" : "age",
              "value" : "6",
              "description" : "",
              "required" : false,
              "dataType" : "Integer",
              "type" : null,
              "defaultValue" : null,
              "validateType" : "",
              "error" : "",
              "expression" : "",
              "children" : [ ]
            } ]
          } ]
        } ]
      } ]
    }, {
      "name" : "timestamp",
      "value" : "1649254781310",
      "description" : "",
      "required" : false,
      "dataType" : "Long",
      "type" : null,
      "defaultValue" : null,
      "validateType" : "",
      "error" : "",
      "expression" : "",
      "children" : [ ]
    }, {
      "name" : "executeTime",
      "value" : "62",
      "description" : "",
      "required" : false,
      "dataType" : "Integer",
      "type" : null,
      "defaultValue" : null,
      "validateType" : "",
      "error" : "",
      "expression" : "",
      "children" : [ ]
    } ]
  }
}
================================
import log;//引入日志模块
import mongoTemplete;//引入自定义的mongoTemplete模块
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.data.domain.PageImpl
import org.apache.commons.collections.CollectionUtils;

import org.springframework.data.mongodb.core.aggregation.Aggregation;

var tableName = "timo_test";

var criteria = Criteria.where("isdel").is(0)
        // .and("store.isdel").is(0)
        .and("_id").is("623d836c8422670a040dcb8b");
var currentPage = 1;
var pageSize = 10;

Query query = new Query(criteria);
var res = mongoTemplete.find(query, tableName);

// 平铺 添加字段 取出子集字段形成新字段添加到结果集 只显示某些字段
// var res = mongoTemplete.aggregate(Aggregation.newAggregation(
//         Aggregation.unwind("store"),
//         Aggregation.match(criteria),//先平铺再加查询条件， 不然子集中的条件不生效
//         Aggregation.skip((currentPage-1)*pageSize),
//         Aggregation.limit(pageSize),
//         // Aggregation.match(Criteria.where("store.isdel").is(0)),
//         Aggregation.addFields()
//             .addField("newField").withValue("我是新建的字段")
//             .addFieldWithValue("storeAge", "$store.age")
//             .addFieldWithValue("storeName", "$store.name")
//             .build(),
//         Aggregation.project("name","age","storeAge","storeName","newField")
//     ),tableName).mappedResults;


//平铺以后--两条数据--分别取出里面的字段
// res = mongoTemplete.aggregate(Aggregation.newAggregation(
//         Aggregation.unwind("$store"),
//         Aggregation.skip((currentPage-1)*pageSize),
//         Aggregation.limit(pageSize),
//         Aggregation.match(criteria),
//         // Aggregation.project("name","age","$store.age")//两个age会出错
//         Aggregation.project("name","age")
//             .and("$store.age").as("storeAge")
//             .and("$store").as("store")//将整个集合作为一个字段
//     ),tableName).mappedResults;    

//平铺以后--分组只取第一条
res = mongoTemplete.aggregate(Aggregation.newAggregation(
        Aggregation.unwind("$store"),
        Aggregation.match(criteria),
        Aggregation.skip((currentPage-1)*pageSize),
        Aggregation.limit(pageSize),
            // Aggregation.sort(Sort.by(orderList)),
        Aggregation.group("_id")//group 自带project效果
            .first("name").as("name")
            .first("age").as("age")
            .first("$store.name").as("storeName")
            //  .addToSet("$eventCircle").as("eventCircle")
            .push("$store").as("store")//将整个集合作为一个字段
    ),tableName).mappedResults;    

if (CollectionUtils.isNotEmpty(res)) {
    res.forEach(o -> {
        o["_id"] = o["_id"].toString()
    });
}

// {
//   "_id" : "423552d95008f0414c57b316",
//   "name" : "姜娜",
//   "cardType" : "2",
//   "cardNo" : "620202198909090909",
//   "sex" : "1",
//   "age" : 23,
//   "mobile" : "13666666666",
//   "addressStr" : "详细地址啦啦啦啦啦啦",
//   "companyName" : "个人单位",
//   "jobTypeName" : "0",
//   "nationality" : "中国",
//   "ethnicChinese" : "0",
//   "streetName" : "",
//   "streetId" : "",
//   "communityName" : "",
//   "communityId" : "",
//   "pcVaccinateName" : "3",
//   "firstVaccinate" : null,
//   "secondVaccinate" : null,
//   "thirdVaccinate" : null,
//   "dataDeptId" : "1010001",
//   "dataDeptName" : "东宝区-教育局",
//   "regionId" : "420802",
//   "regionName" : "东宝区",
//   "dangerType" : "1",
//   "checkedFlag" : 0,
//   "pcNucleicAcName" : "",
//   "pcNucleicAcid" : "",
//   "pcAcidCheckTime" : "",
//   "createTime" : "2022-03-19T03:49:45.000Z",
//   "updateTime" : ISODate("2022-03-20T11:58:59.901Z"),
//   "delFlag" : 0,
//   "address" : "详细地址啦啦啦啦啦啦",
//   "deptName" : "教育局",
//   "dangerTypeName" : "其他人员",
//   "eventNucleicAcid" : [{
//       "collectSiteId" : 1,
//       "collectLocationId" : 1,
//       "collectSpecimenTypeId" : 1,
//       "remark" : "",
//       "collectSiteName" : "1",
//       "collectLocationName" : "",
//       "collectTime" : ISODate("2022-03-22T08:45:31.151Z"),
//       "samplingCompany" : "",
//       "samplingCompanyName" : "华西天府医院",
//       "batch" : "1",
//       "collectPlace" : "钟祥市旧口镇卫生院罗集分院",
//       "cardType" : "2",
//       "cardNo" : "620202198909090909",
//       "result" : "0",
//       "resultStr" : "阴性",
//       "phoneNumber" : "123446",
//       "_id" : "423575350276535968",
//       "createTime" : "2022-03-19T07:28:26.000Z",
//       "updateTime" : "2022-03-20T09:32:24.080Z",
//       "delFlag" : 0
//     }, {
//       "collectSiteId" : 1,
//       "collectLocationId" : 1,
//       "collectSpecimenTypeId" : 1,
//       "remark" : "",
//       "collectSiteName" : "1",
//       "collectLocationName" : "",
//       "collectTime" : ISODate("2022-03-21T08:45:31.151Z"),
//       "samplingCompany" : "",
//       "samplingCompanyName" : "钟祥市人民医院",
//       "batch" : "1",
//       "collectPlace" : "钟祥市旧口镇卫生院罗集分院",
//       "cardType" : "2",
//       "cardNo" : "620202198909090909",
//       "result" : "0",
//       "resultStr" : "阴性",
//       "phoneNumber" : "123446",
//       "_id" : "423575350276535968",
//       "createTime" : "2022-03-19T07:28:26.000Z",
//       "updateTime" : "2022-03-20T09:32:24.080Z",
//       "delFlag" : 0
//     }],
//   "eventCircle" : [{
//       "cycleCount" : "1",
//       "cycleStartDate" : ISODate("2022-03-23T03:15:11.857Z"),
//       "cycleEndDate" : ISODate("2022-03-25T03:15:11.857Z")
//     }, {
//       "cycleCount" : "2",
//       "cycleStartDate" : ISODate("2022-03-24T03:15:11.857Z"),
//       "cycleEndDate" : ISODate("2022-03-24T03:15:11.857Z")
//     }]
// }
// 数据库：10.128.173.171:27027 cloudwalk_yqfk_dev test_jingmen_xh
// 现有一条人员信息，按该人员核酸检测事件（eventNucleicAcid）的采集时间（collectTime）取最新检测单位（samplingCompanyName）放在主信息中
// 并且按周期事件（eventCircle）的周期结束时间（cycleEndDate）正序取出周期事件
// 最后将姓名，身份证号，手机号，检测单位，周期事件返回
// var tableName = "test_jingmen_xh";
// var coSort = Sort.by(Sort.Order.desc("$eventNucleicAcid.collectTime"),Sort.Order.desc("$eventCircle.cycleEndDate"));

// var res = mongoTemplete.aggregate(Aggregation.newAggregation(
//         Aggregation.unwind("$eventNucleicAcid"),
//         Aggregation.unwind("$eventCircle"),
//         Aggregation.sort(coSort),
//         Aggregation.group("_id")//group 自带project效果
//             .first("name").as("name")
//             .first("cardNo").as("cardNo")
//             .first("mobile").as("mobile")
//             .first("$eventNucleicAcid.samplingCompanyName").as("samplingCompanyName")
//             .addToSet("$eventCircle").as("eventCircle")
//     ),tableName).mappedResults; 

return res;